package com.example.pm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.pm.common.basic.perm.PermInter;
import com.example.pm.common.constant.SystemConstant;
import com.example.pm.common.result.R;
import com.example.pm.common.utils.ClassUtils;
import com.example.pm.domain.Model.UserPerm;
import com.example.pm.domain.Perm;
import com.example.pm.domain.Role;
import com.example.pm.domain.User;
import com.example.pm.mapper.PermMapper;
import com.example.pm.mapper.RoleMapper;
import com.example.pm.mapper.UserMapper;
import com.example.pm.mapper.UserPermMapper;
import com.example.pm.service.PermService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermServiceImpl implements PermService {
    @Autowired
    private PermMapper permMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPermMapper userPermMapper;

    @Override
    @SneakyThrows
    public void createPermRedis() {
        List<Perm> perms = new ArrayList<>();
        Integer jb = roleMapper.selectList(new LambdaQueryWrapper<>()).stream().max(Comparator.comparing(Role::getAccess)).get().getAccess();

        String packagePath = SystemConstant.ControllerPath;
        // 获取包下所有的类
        List<Class<?>> classes = ClassUtils.getClzFromPkg(packagePath);

//        List<Class<?>> classes = getClasses(packagePath);
        classes.stream().peek(c -> {
            Method[] methods = c.getDeclaredMethods();
            for (Method method : methods) {
                PermInter inter = method.getDeclaredAnnotation(PermInter.class);
                if (inter != null) {
                    Perm perm = new Perm();
                    perm.setJsjb(Integer.parseInt(inter.jsjb()));
                    perm.setName(inter.name());
                    perm.setPerm(inter.perm());
                    if (perm.getJsjb() == 0) perm.setJsjb(jb);
                    perms.add(perm);
                }
            }

        }).collect(Collectors.toList());

        this.createUserPermList(perms);

        permMapper.insertList(perms);
    }

    @Override
    public List<Perm> getList() {
        return permMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public List<String> getListByZh(String zh) {
        LambdaQueryWrapper<UserPerm> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserPerm::getZh, zh);
        return userPermMapper.selectList(lqw).stream().map(UserPerm::getPerm).collect(Collectors.toList());
    }

    @Override
    public R<String> changePermForEmployee(String zh, List<String> perm) {
        LambdaQueryWrapper<UserPerm> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserPerm::getZh, zh);
        userPermMapper.delete(lqw);

        List<UserPerm> list = perm.stream().map(o -> {
            UserPerm userPerm = new UserPerm();
            userPerm.setPerm(o);
            userPerm.setZh(zh);
            return userPerm;
        }).collect(Collectors.toList());

        userPermMapper.insertList(list);
        return R.ok("操作成功");
    }

    //将账号和权限关联起来
    @Async
    public void createUserPermList(List<Perm> perms) {
        List<UserPerm> list1 = userPermMapper.selectList(new LambdaQueryWrapper<>());

        userPermMapper.delete(new LambdaQueryWrapper<>());

        List<UserPerm> list = new ArrayList<>();

        List<Role> roleList = roleMapper.selectList(new LambdaQueryWrapper<>());
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<>());

        userList.stream().peek(o -> {
            Integer access = roleList.stream().filter(r -> r.getId().equals(o.getRoleId())).collect(Collectors.toList()).get(0).getAccess();
            List<Perm> permList = perms.stream().filter(p -> p.getJsjb() >= access).collect(Collectors.toList());
            for (Perm perm : permList) {
                UserPerm userPerm = new UserPerm();
                userPerm.setZh(o.getZh());
                userPerm.setPerm(perm.getPerm());
                list.add(userPerm);
            }
        }).collect(Collectors.toList());

        list1.addAll(list);
        list1 = list1.stream().peek(o -> o.setId(null)).distinct().collect(Collectors.toList());

        userPermMapper.insertList(list1);
    }


    // 获取包下所有的类
    private List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
        List<Class<?>> classes = new ArrayList<>();
        String packagePath = packageName.replace('.', '/');
        Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packagePath);
        List<File> dirs = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes;
    }

    // 在指定的目录下查找类文件
    private List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                Class<?> clazz = Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6));
                classes.add(clazz);
            }
        }
        return classes;
    }
}
